﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Lacrima.Framework.Infrastructure
{
    public static class MD5Provider
    {
        private static MD5 _provider { get; set; }

        public static MD5 provider
        {
            get
            {
                if (_provider == null)
                {
                    _provider = new MD5CryptoServiceProvider();
                }
                return _provider;
            }
        }

        /// <summary>
        /// 创建模板字符串的MD5哈希值
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>System.String.</returns>
        public static string GetHashCode(string target, string encoding = "UTF-8")
        {
            byte[] result = Encoding.GetEncoding(encoding).GetBytes(target);   
            byte[] output = provider.ComputeHash(result);
            return BitConverter.ToString(output).TrimCharSet('-');
        }

        /// <summary>
        /// 创建模板字符串的MD5哈希值
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>System.String.</returns>
        public static string GetFileHashCode(string filePath)
        {
            using (FileStream fStream = new FileStream(filePath, FileMode.Open))
            {
                byte[] output = provider.ComputeHash(fStream);
                return BitConverter.ToString(output).TrimCharSet('-');
            }
        }
    }
}
